/*
 * ========================================================
 * Copyright(c) 2014 杭州龙骞科技-版权所有
 * ========================================================
 * 本软件由杭州龙骞科技所有, 未经书面许可, 任何单位和个人不得以
 * 任何形式复制代码的部分或全部, 并以任何形式传播。
 * 公司网址
 * http://www.hzdracom.com/
 * ========================================================
 */
package com.shwread.android.qysw.activity;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.shwread.android.qysw10000204.R;
import com.shwread.http.base.TextHttpResponseHandler;
import com.shwread.httpsdk.http.callback.ActionListener;
import com.shwread.httpsdk.util.SimpleXmlHelper;

import org.apache.http.Header;
import org.apache.http.util.ByteArrayBuffer;
import org.apache.http.util.EncodingUtils;
import org.geometerplus.android.util.QyreaderPerferencesUtil;
import org.xml.sax.SAXException;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import logic.bean.BookBean;
import logic.bean.TOCItem;
import logic.beanenum.BookStatus_Enum;
import logic.constants.Const;
import logic.constants.DefaultConsts;
import logic.dao.BookDao;
import logic.util.FileUtil;
import logic.util.Util;
import logic.util.logutil.LogUtil;
import logic.util.qryChapterInfoUtil;
import logic.xml.parser.NCXHandler;


/**
 * @Project： Lqyd_Android
 * @Title：ReadingmagazineActivity
 * @Description：
 * @Author：wayne
 * @Date：2014年8月31日上午11:54:53
 */
public class ReadingmagazineActivity
        extends
        BaseBusinessActivity
        implements
        OnClickListener,
        OnTouchListener,
        OnGestureListener,
        OnPageChangeListener
{
	
	private static final int        UPDATEUI_MAGAZINE_TEXT            = 100;
	private static final int        UPDATEUI_MAGAZINE_ONLINE_DOWNLOAD = UPDATEUI_MAGAZINE_TEXT + 1;
	/* View */
	private TextView                tvMagazineText;
	private TextView                tvMagazineTime;
	private ImageView               ivMagazineUp;
	private ScrollView              svMagazineText;
	private View                    vMagazineUp;
	private GestureDetector         gestureDetector                   = null;
	private ViewPager               vpMagazineView;
	private AdapterPager            adapter;
	
	private List<TOCItem>           catoryList;
	private List<String[]>          chapterList;
	
	private int                     chapterIndex;
	//	private UpdateBookLastOpenTimeAction<BaseBusinessActivity> updateBookLastOpenTimeAction;
	
	private Context                 mContext;
	private BookBean                bean;
	
	private QyreaderPerferencesUtil qyreaderUtil;
	private int                     downloadCount                     = 0;
	
	private Handler                 handler                           = new Handler()
	                                                                  {
		                                                                  
		                                                                  @Override
		                                                                  public void handleMessage(Message msg) {
			                                                                  switch (msg.what) {
																				  case UPDATEUI_MAGAZINE_TEXT:
																					  tvMagazineText.setText(myString);
																					  break;
																				  case UPDATEUI_MAGAZINE_ONLINE_DOWNLOAD:
																					  downloadCount = qyreaderUtil.getDownloadChapterindex(String.valueOf(bean.book_id));
																					  if (downloadCount < catoryList.size()) chapterList.add(xmlUnEscape(downloadCount));
																					  adapter.notifyDataSetChanged();
																					  System.out.println("~~~~~~notifyView~~~~~~downloadCount:~~" + downloadCount);
																					  if (downloadCount < catoryList.size()) {
//																						  new QryChapterInfoAction(mContext, String.valueOf(bean.book_id), catoryList.get(downloadCount).getId(), downloadCount, new ChapterInfoListener()).start();
																						  new qryChapterInfoUtil().qryChapterInfo(mContext, String.valueOf(bean.book_id), catoryList.get(downloadCount).getId(), downloadCount, new ChapterInfoHandler());
																					  }
																					  break;
																				  default:
																					  break;
																			  }
																		  }
																		  
	                                                                  };
	
	@Override
	public Handler getUIHandler() {
		return handler;
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = this;
		setContentView(R.layout.magazine_read_lay);
		startTime = System.currentTimeMillis();
		qyreaderUtil = QyreaderPerferencesUtil.getInstance(mContext, Const.phone_number);
		if (getIntent().hasExtra("BookMarkBean"))
		{
			bean = (BookBean) getIntent().getSerializableExtra("BookMarkBean");
		}
		chapterIndex = getIntent().getIntExtra(DefaultConsts.chapterId_index_i, 0);
		if (bean == null)
		{
			Util.showToast(this, "书籍已下架");
			finish();
			return;
		}
		
//		mAService = new ATaskService();
//		mAService.startAService(this);
		
		downloadCount = qyreaderUtil.getDownloadChapterindex(String.valueOf(bean.book_id));
		initData();
		setAdapterDate();
		initView();
		setListener();
		
	}
	private long startTime,endTime;
	/** 更新章节信息 */
	private void updateChapter(long chapterId){
		bean.server_chapterid = chapterId;
		bean.startTime = startTime;
		bean.endTime = endTime;
		bean.account=Const.phone_number;
		final String chapterName = catoryList.get(chapterIndex).getNavLabel();
		bean.chapterName = Util.isEmpty(chapterName)?"--":chapterName;
		BookDao.getInstance(mContext).addBooktoShelf(bean);
	}
	@Override
	protected void onStop() {
	    super.onStop();
	    endTime = System.currentTimeMillis();
	    final String chapterId = catoryList.get(chapterIndex).getId(); 
		if(Util.isNotEmpty(chapterId)){
			//更新阅读章节信息
			updateChapter(Long.valueOf(chapterId));
		}
	}
	@Override
	protected void onDestroy() {
	    super.onDestroy();
//	    if(mAService!=null){
//	    	mAService.stopAService();
//	    	mAService = null;
//	    }
	}
	
	void initData() {
		initDirctory(BookStatus_Enum.ONLINE.getValue());
		chapterList = new ArrayList<String[]>(catoryList.size());
		adapter = new AdapterPager();
	}
	
	void setAdapterDate() {
		if (downloadCount > 0)
		{
			for (int i = 0; i < downloadCount; i++)
			{
				chapterList.add(xmlUnEscape(i));
			}
			if (downloadCount < catoryList.size()) {
//				new QryChapterInfoAction(mContext, String.valueOf(bean.book_id), catoryList.get(downloadCount).getId(), downloadCount + 1, new ChapterInfoListener()).start();
				new qryChapterInfoUtil().qryChapterInfo(mContext, String.valueOf(bean.book_id), catoryList.get(downloadCount).getId(),downloadCount + 1,new ChapterInfoHandler());
			}
		}
		else
		{
			chapterList.add(xmlUnEscape(0));
//			new QryChapterInfoAction(mContext, String.valueOf(bean.book_id), catoryList.get(downloadCount).getId(), 0, new ChapterInfoListener()).start();
			new qryChapterInfoUtil().qryChapterInfo(mContext, String.valueOf(bean.book_id), catoryList.get(downloadCount).getId(),0,new ChapterInfoHandler());
		}
	}
	
	void initView() {
		tvMagazineText = (TextView) findViewById(R.id.magazine_text);
		svMagazineText = (ScrollView) findViewById(R.id.magazine_text_scrollview);
		tvMagazineText.setVisibility(View.GONE);
		svMagazineText.setVisibility(View.GONE);
		ivMagazineUp = (ImageView) findViewById(R.id.magazine_image_up);
		tvMagazineTime = (TextView) findViewById(R.id.magazine_time);
		vMagazineUp = (View) findViewById(R.id.magazine_image_up_view);
		vpMagazineView = (ViewPager) findViewById(R.id.magazine_view);
		vpMagazineView.setAdapter(adapter);
		tvMagazineTime.setText(getTitle(chapterIndex));
		vpMagazineView.setCurrentItem(chapterIndex);
	}
	
	void setListener() {
		svMagazineText.setOnTouchListener(this);
		vMagazineUp.setOnTouchListener(this);
		tvMagazineText.setOnClickListener(this);
		ivMagazineUp.setOnClickListener(this);
		ivMagazineUp.setOnTouchListener(this);
		vpMagazineView.setOnPageChangeListener(this);
	}
	
	private String getTitle(int chapterindex) {
		String titleStr = "";
		if (chapterindex == 0)
		{
			titleStr = bean.book_name + " 封面 " + Util.getTimeByDuration(System.currentTimeMillis());
		}
		else if (chapterindex == (catoryList.size() - 1))
		{
			titleStr = bean.book_name + " 封底 " + Util.getTimeByDuration(System.currentTimeMillis());
		}
		else
		{
			int total = catoryList.size() - 2;
			titleStr = bean.book_name + " 第" + chapterindex + "/" + total + "页 " + Util.getTimeByDuration(System.currentTimeMillis());
		}
		
		return titleStr;
		
	}
	
	private void initDirctory(int status) {
		String dirctory = "";
		if (status == BookStatus_Enum.ONLINE.getValue())
		{
			
			dirctory = FileUtil.OnlinePath(String.valueOf(bean.book_id)) + FileUtil.Book_CATALOGUE;
		}
		else if (status == BookStatus_Enum.LOCAL.getValue())
		{
			dirctory = FileUtil.DownloadPath() + bean.book_id + "/META-INF/book.ncx";
		}
		SAXParserFactory factory = SAXParserFactory.newInstance();
		SAXParser parser;
		try
		{
			parser = factory.newSAXParser();
			InputStream is = new FileInputStream(new File(dirctory));
			NCXHandler handle = new NCXHandler();
			parser.parse(is, handle);
			is.close();
			catoryList = handle.getNavPointList();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		catch (ParserConfigurationException e)
		{
			e.printStackTrace();
		}
		catch (SAXException e)
		{
			e.printStackTrace();
		}
	}
	
	private String[] xmlUnEscape(int indexChapter) {
		String[] result = new String[2];
		String chapterId = catoryList.get(indexChapter).getId();
		if (FileUtil.exists(FileUtil.OnlinePath(String.valueOf(bean.book_id)) + chapterId + ".html"))
		{
			String xml = FileUtil.readSDFileToString(FileUtil.OnlinePath(String.valueOf(bean.book_id)) + chapterId + ".html");
			String imgUrl = SimpleXmlHelper.getPropValue(xml, "src");
			String txtUtl = SimpleXmlHelper.getPropValue(xml, "href");
			result[0] = SimpleXmlHelper.xmlUnEscape(imgUrl);
			result[1] = SimpleXmlHelper.xmlUnEscape(txtUtl);
		}
		else
		{
			result[0] = "";
			result[1] = "";
		}
		return result;
	}
	
	String myString = "";
	
	private String loadTxt(final String url) {
		new Thread()
		{
			public void run() {
				try
				{
					// 定义获取文件内容的URL  
					URL myURL = new URL(url);
					// 打开URL链接  
					URLConnection ucon = myURL.openConnection();
					// 使用InputStream，从URLConnection读取数据  
					InputStream is = ucon.getInputStream();
					BufferedInputStream bis = new BufferedInputStream(is);
					// 用ByteArrayBuffer缓存  
					ByteArrayBuffer baf = new ByteArrayBuffer(50);
					int current = 0;
					while ((current = bis.read()) != -1)
					{
						baf.append((byte) current);
					}
					// 将缓存的内容转化为String,用UTF-8编码  
					myString = EncodingUtils.getString(baf.toByteArray(), "UTF-8");
					handler.sendEmptyMessage(UPDATEUI_MAGAZINE_TEXT);
				}
				catch (Exception e)
				{
					myString = e.getMessage();
				}
			}
		}.start();
		
		return myString;
	}
	
	private class AdapterPager
	        extends
	        PagerAdapter
	{
		
		@Override
		public int getItemPosition(Object object) {
			return POSITION_NONE;
		}
		
		@Override
		public int getCount() {
			return chapterList.size();
		}
		
		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}
		
		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			ImageView iv = new ImageView(mContext);
			try
			{
				System.out.println("---当前position:"+position);
				final String url = chapterList.get(position)[0];
				System.out.println("---当前url:"+url);
				String name = String.valueOf(chapterList.get(position).hashCode());
				System.out.println("---当前name:"+name);
				Util.loadImg(mContext, name, url, iv);
			}
			catch (OutOfMemoryError e)
			{
				e.printStackTrace();
			}
			((ViewPager) container).addView(iv, 0);
			return iv;
		}
		
		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView((View) object);
		}
	}
	
	@Override
	public void onPageScrollStateChanged(int arg0) {
		
	}
	
	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
		System.out.println("onPageScrolled position " + arg0);
		if ((arg0 + 1) == catoryList.size()) { return; }
		
	}
	
	@Override
	public void onPageSelected(int arg0) {
		System.out.println("~~~~~~~~onPageSelected~~~~~~~~:" + arg0);
		chapterIndex = arg0;
		qyreaderUtil.setChapterIndex(String.valueOf(bean.book_id), arg0);
		tvMagazineTime.setText(getTitle(arg0));
		if (Util.isEmpty(chapterList.get(arg0)[1]))
		{
			ivMagazineUp.setVisibility(View.GONE);
			vMagazineUp.setVisibility(View.GONE);
		}
		else
		{
			ivMagazineUp.setVisibility(View.VISIBLE);
			vMagazineUp.setVisibility(View.VISIBLE);
			loadTxt(chapterList.get(arg0)[1]);
			//tvMagazineText.loadUrl(chapterList.get(position)[1]);
		}
	}
	
	@Override
	public boolean onDown(MotionEvent e) {
		return false;
	}
	
	@Override
	public void onShowPress(MotionEvent e) {
		
	}
	
	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		return false;
	}
	
	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
		return false;
	}
	
	@Override
	public void onLongPress(MotionEvent e) {
		
	}
	
	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
		return true;
	}
	
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		if (v == ivMagazineUp || v == vMagazineUp)
		{
			switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					LogUtil.d("zzh", "ACTION_DOWN");
					break;
				case MotionEvent.ACTION_UP:
					LogUtil.d("zzh", "ACTION_UP");
					tvMagazineText.setVisibility(View.VISIBLE);
					svMagazineText.setVisibility(View.VISIBLE);
					svMagazineText.fullScroll(ScrollView.FOCUS_UP);
					tvMagazineText.setAnimation(AnimationUtils.loadAnimation(mContext, R.anim.activity_push_bottom_in));
					svMagazineText.setAnimation(AnimationUtils.loadAnimation(mContext, R.anim.activity_push_bottom_in));
					break;
				case MotionEvent.ACTION_CANCEL:
					LogUtil.d("zzh", "ACTION_CANCEL");
					tvMagazineText.setVisibility(View.VISIBLE);
					svMagazineText.setVisibility(View.VISIBLE);
					svMagazineText.fullScroll(ScrollView.FOCUS_UP);
					tvMagazineText.setAnimation(AnimationUtils.loadAnimation(mContext, R.anim.activity_push_bottom_in));
					svMagazineText.setAnimation(AnimationUtils.loadAnimation(mContext, R.anim.activity_push_bottom_in));
					break;
				
				default:
					break;
			}
		}
		else if (v == svMagazineText)
		{
			switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					
					break;
				case MotionEvent.ACTION_UP:
					if (v.getScrollY() <= 0)
					{
						tvMagazineText.setVisibility(View.GONE);
						svMagazineText.setVisibility(View.GONE);
						tvMagazineText.setAnimation(AnimationUtils.loadAnimation(mContext, R.anim.activity_push_bottom_out));
						svMagazineText.setAnimation(AnimationUtils.loadAnimation(mContext, R.anim.activity_push_bottom_out));
					}
					break;
				
				default:
					break;
			}
		}
		else
		{
			return gestureDetector.onTouchEvent(event);
		}
		
		return false;
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.magazine_image_up:
				tvMagazineText.setVisibility(View.VISIBLE);
				svMagazineText.setVisibility(View.VISIBLE);
				svMagazineText.fullScroll(ScrollView.FOCUS_UP);
				tvMagazineText.setAnimation(AnimationUtils.loadAnimation(mContext, R.anim.activity_push_bottom_in));
				svMagazineText.setAnimation(AnimationUtils.loadAnimation(mContext, R.anim.activity_push_bottom_in));
				break;
			case R.id.magazine_text:
				tvMagazineText.setVisibility(View.GONE);
				svMagazineText.setVisibility(View.GONE);
				tvMagazineText.setAnimation(AnimationUtils.loadAnimation(mContext, R.anim.activity_push_bottom_out));
				svMagazineText.setAnimation(AnimationUtils.loadAnimation(mContext, R.anim.activity_push_bottom_out));
				break;
			default:
				break;
		}
		
	}
	
	private class ChapterInfoHandler extends TextHttpResponseHandler{

		@Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
	        
        }

		@Override
        public void onSuccess(int statusCode, Header[] headers, String responseString) {
			handler.sendEmptyMessage(UPDATEUI_MAGAZINE_ONLINE_DOWNLOAD);
        }
		
	}
	
	
	private class ChapterInfoListener
	        implements
	        ActionListener
	{
		
		@Override
		public void OK(Object obj) {
			handler.sendEmptyMessage(UPDATEUI_MAGAZINE_ONLINE_DOWNLOAD);
		}
		
		@Override
		public void ERROR(int resultCode, String message) {
			
		}
		
		@Override
		public void HTTPERROR(int statusCode) {
			
		}
		
	}
	
}
